package com.lagou.study.filter;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.*;

public class IpGatewayFilter implements GatewayFilter, Ordered {

    private static Map<String, List<Date>> ipMap = new HashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        RequestPath path = request.getPath();
        System.out.println(path);
        if("/api/user/register".equals(path.toString())){
            String host = request.getRemoteAddress().getHostString();
            Date now = new Date();
            if (ipMap.get(host) == null){
                List<Date> list = new ArrayList();
                list.add(now);
                ipMap.put(host, list);
            }else {
                ipMap.get(host).add(now);
            }
            Date oneMinBefore = DateUtils.addMinutes(now, -1);
            for (int i = 0; i < ipMap.get(host).size(); i++) {
                if (ipMap.get(host).get(i).compareTo(oneMinBefore)==-1){
                    ipMap.get(host).remove(ipMap.get(host).get(i));
                }
            }
            int count = ipMap.get(host).size();
            if (count>100){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                String data = "count 100 more,try again after.";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }else {
                return chain.filter(exchange);
            }
        }else {
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
